package com.qianfeng.smartdevices.service.impl;

import com.qianfeng.smartdevices.pojo.BaseUser;
import com.qianfeng.smartdevices.pojo.User;
import com.qianfeng.smartdevices.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class MyUserDetailsService implements UserDetailsService {

    private UserService userService;
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.findUserByUserName(username);
        if(user == null) {
            throw new UsernameNotFoundException("用户名或者密码错误");
        }
        if (user.getStatus().equals("0")) {
            throw new DisabledException("用户被禁");
        }
        BaseUser baseUser = new BaseUser(username, user.getPassword(), new ArrayList<>());
        baseUser.setUid(user.getId());
        return baseUser;
    }
}
